package com.jackson0714.passjava.member.config;

import com.fasterxml.jackson.databind.json.JsonMapper;
import com.google.common.base.Objects;
import com.jackson0714.common.exception.FeignBadRequestException;
import com.jackson0714.common.utils.JsonUtils;
import com.jackson0714.common.utils.R;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
  * @Description: feign 保留原始异常信息  重写feign的异常编码器,只有异常的额请求会进入此逻辑
  * @Version v1.0.0
  * @author zhangpeng148
  * @date 2022/1/21 11:09
  */
@Configuration
@Slf4j
public class FeignErrorMsgConfig {

    public static final JsonUtils jsonUtils= new JsonUtils();

    @Bean
    public ErrorDecoder errorDecoder(){
        return new OriginalErrorDecoder();
    }

    public class OriginalErrorDecoder implements ErrorDecoder {

        @Override
        public Exception decode(String s, Response response) {
            Exception exception = null;
            if(HttpStatus.SC_OK != response.status()){
                try {
                    // 获取原始的返回内容
                    String json = Util.toString(response.body().asReader());
                    exception = new RuntimeException(json);
                    // 将返回内容反序列化为Result，这里应根据自身项目作修改
                    R result = jsonUtils.fromJson(json, R.class);
                    // 业务异常抛出简单的 RuntimeException，保留原来错误信息
                    if (!Objects.equal(result.get("code"),0)) {
                        //该异常继承HystrixBadRequestException  就算打开熔断也不会被hytrix吞掉  会直接抛出异常不走熔断
                        exception = new FeignBadRequestException(result.get("code"),result.get("msg"));
                    }
                } catch (IOException ex) {
                    log.error("feign处理异常:{}",ex.getMessage(), ex);
                }
                return exception;
            }

            return new FeignBadRequestException(999,"unknown error");
        }
    }
}
